#!/bin/sh
set -e

[ -f /etc/blazegraph/blazegraph ] && . /etc/blazegraph/blazegraph

JAVA=`which java 2> /dev/null` || true

if [ -z "$JAVA" ] ; then

	echo ""
	echo "***************************************************************************************"
	echo "* It does not appear that java is installed.                                          *"
	echo "* It is recommended that you install Oracle JDK 7, which is officially supported.     *"
	echo "*                                                                                     *"
	echo "* http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html *"
	echo "*                                                                                     *"
	echo "* However, to run with openjdk use:  yum install -y java-1.7.0-openjdk-devel          *"
	echo "*                                                                                     *"
	echo "* You must install JAVA to start Blazegraph.                                          *"
	echo "*                                                                                     *"
	echo "* Once java is installed run:  service blazegraph start                               *"
	echo "***************************************************************************************"
	echo ""

fi

        [ -z "$NAME" ] && NAME="blazegraph"
        [ -z "$BLZG_USER" ] && BLZG_USER="blzg"
        [ -z "$BLZG_GROUP" ] && BLZG_GROUP="blzg"
        [ -z "$BLZG_DATA" ] && BLZG_DATA="/var/lib/$NAME"
        [ -z "$BLZG_LOG" ] && BLZG_LOG="/var/log/$NAME"

        # Add the blazegraph group
        groupadd -f -r "$BLZG_GROUP" >& /dev/null

        # Add the blazegraph user with the home directory
        # Allow the home directory to be created later by the installer
        if ! getent passwd "$BLZG_USER" > /dev/null 2>&1 ; then
		    useradd -r -g "$BLZG_USER" -d /usr/share/$NAME -s /sbin/nologin blzg >& /dev/null
        fi

        # Make the blazegraph data and log directories here
        # instead of as a jdeb template to allow overriding of user/group
        # if /etc/default/blazegraph is in place before installation.
        if [ ! -d "$BLZG_DATA" -a ! -L "$BLZG_DATA" ]; then
            mkdir -p $BLZG_DATA
        fi

        if [ ! -d "$BLZG_LOG" -a ! -L "$BLZG_LOG" ]; then
            mkdir -p $BLZG_LOG
        fi

        chown -R $BLZG_USER:$BLZG_GROUP $BLZG_DATA
        chown $BLZG_USER:$BLZG_GROUP $BLZG_LOG


		echo ""
		echo "***********************************************************"
		echo "* The following kernel tuning parameters are recommended. *"
		echo "* They are not automatically configured.                  *"
		echo "***********************************************************"
		echo ""
		#Enable TCP_TW_REUSE
		echo "echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse"
		#Set VM swappiness to 0
		echo "echo "vm.swappiness = 0" >> /etc/sysctl.d/10-vm.swappiness.conf"
		echo "sysctl -p || true >& /dev/null"
